package mybook.dao;

import java.util.List;
import org.springframework.jdbc.core.JdbcTemplate;

import jgo.plugins.jdbc.JdbcTemplatePlugin;
import mybook.model.Book;

public class BookDao {
    public static final BookDao instance = new BookDao();
    JdbcTemplate jdbcTemplate;

    public BookDao() {
        jdbcTemplate = JdbcTemplatePlugin.instance.jdbcTemplate;
    }

    public List<Book> getAllBooks() {
        String sql = "SELECT * FROM books";
        return jdbcTemplate.query(sql, (rs, rowNum) -> new Book(
            rs.getInt("id"),
            rs.getString("title"),
            rs.getString("author")
        ));
    }

    public Book getBookById(int id) {
        String sql = "SELECT * FROM books WHERE id = ?";
        return jdbcTemplate.queryForObject(sql, new Object[]{id}, (rs, rowNum) -> new Book(
            rs.getInt("id"),
            rs.getString("title"),
            rs.getString("author")
        ));
    }

    public void addBook(Book book) {
        String sql = "INSERT INTO books (title, author) VALUES (?, ?)";
        jdbcTemplate.update(sql, book.title, book.author);
    }

    public void updateBook(Book book) {
        String sql = "UPDATE books SET title = ?, author = ? WHERE id = ?";
        jdbcTemplate.update(sql, book.title, book.author, book.id);
    }

    public void deleteBook(int id) {
        String sql = "DELETE FROM books WHERE id = ?";
        jdbcTemplate.update(sql, id);
    }
}